package com.warrior.util;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 定义一个新的视图层写入webpath
 * Created by Shawn on 2017/3/28.
 */
public class CModelAndView extends ModelAndView {

    /**
     * 普通视图，根据velocity配置文件的路径直接加载视图
     */
    public CModelAndView(String viewName) {
        super.setViewName(viewName);
    }

    public CModelAndView(String viewName, HttpServletRequest request, HttpServletResponse response){
        String webPath = this.getURL(request);
        super.addObject("current_webPath", webPath);
        super.setViewName(viewName);
        super.addObject("webPath", webPath);
        String query_url = "";
        if (request.getQueryString() != null
                && !request.getQueryString().equals("")) {
            query_url = "?" + request.getQueryString();
        }
        super.addObject("current_url", request.getRequestURI() + query_url);
    }


    private static String getURL(HttpServletRequest request) {
        String contextPath = request.getContextPath().equals("/") ? ""
                : request.getContextPath();
        String url = "http://" + request.getServerName();
        if (request.getServerPort() != 80) {
            url = url + ":" + request.getServerPort() + contextPath;
        } else {
            url = url + contextPath;
        }
        return url;
    }

}


